<?php

namespace app\admin\controller;
use think\Db;
use think\Page;
use app\admin\logic\GoodsLogic;
use app\admin\model\Goods;
use think\AjaxPage;
class Ad extends Base{
    public function ad(){       
        $ad_id = I('get.aid/d',0);
         
        $ad_info = array();
		$storeid = session('store_id');	
		$where['storeid'] = $storeid;	
		
		$atype = D('ad_type')->select();
		$this->assign('atype',$atype);
        if($ad_id){
            $ad_info = D('ad')->where('aid',$ad_id)->find();  
			$goods = M('goods')->where('id' , $ad_info['goodsid'])->getField("gname,price,id,icon");
	        $this->assign('info',$ad_info);
			$this->assign('a_goods',$goods);
        }
		
        return $this->fetch();
    }
    
    public function adList(){
        
        delFile(RUNTIME_PATH.'html'); // 先清除缓存, 否则不好预览

        $Ad =  M('ad');         
        $atype = I('atype',0);
        if($atype){
            $where['atype'] = $atype;
        	$this->assign('atype',I('atype'));
        }
		
		$storeid = session('store_id');	
		$where['storeid'] = $storeid;		
		
        $keywords = I('keywords/s',false,'trim');
        if($keywords){
            $where['ad_name'] = array('like','%'.$keywords.'%');
        }
        $count = $Ad->where($where)->count();// 查询满足要求的总记录数
        $Page = $pager = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $res = $Ad->where($where)->order('atype desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $list = $res;
                                     
        $adtypelist = M('ad_type')->select();
		$ad_type_list = M('ad_type')->getField("atypeid,atypename");          
//		var_dump($adtypelist);
		                 
        $this->assign('ad_type',$adtypelist);//广告位 
        $this->assign('atplist',$ad_type_list);//广告位 
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$pager);     

        //判断API模块存在
        if(is_dir(APP_PATH."/api")) $this->assign('is_exists_api',1);
       
        
        return $this->fetch();
    }
    
    public function position(){
        $act = I('get.act','add');
        $position_id = I('get.position_id/d');
        $info = array();
        if($position_id){
            $info = D('ad_position')->where('position_id',$position_id)->find();
        }
        $this->assign('info',$info);
        $this->assign('act',$act);
        return $this->fetch();
    }

    public function positionList()
    {
        $count = Db::name('ad_position')->count();// 查询满足要求的总记录数
        $Page = $pager = new Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数
        $list = Db::name('ad_position')->order('position_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->assign('pager', $Page);
        return $this->fetch();
    }
    
	
	//删除广告
	public function addel(){
		$data = I('post.');
		$r = D('ad')->where('aid', $data['del_id'])->delete();
        if($r){
            $this->ajaxReturn(['status'=>1,'msg'=>"操作成功",'data' =>['url'=>U("Admin/Ad/adList")]]);
        }else{
            $this->ajaxReturn(['status'=>-1,'msg'=>"操作失败"]);
        }
	}
	
    public function adHandle(){
    	$data = I('post.');

		$aid = I('aid/d',0);
		
		
        $validate = \think\Loader::validate('Ad');
        if (!$validate->batch()->check($data)) {
            $error = $validate->getError();
            $error_msg = array_values($error);
            $return_arr = array(
                'status' => -1,
                'msg' => $error_msg[0],
                'data' => $error,
            );
            $this->ajaxReturn($return_arr);
        }
		
		$storeid = session('store_id');	
		$data['storeid'] = $storeid;
    	if($aid == 0){
    		$data['isshow'] = 1;   		
    		$r = D('ad')->add($data);
    	}
		else{
    		$r = D('ad')->where('aid', $data['aid'])->save($data);
    	}
    	
//		$this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storegoods/activitylist")]);
		
    	if($r){
//  		$this->success("操作成功",U('Admin/Ad/adList'));
			$this->ajaxReturn(['status' => 1,'msg' => '操作成功','data' =>['url'=>U("Admin/Ad/adList")]]);
    	}else{
//  		$this->error("操作失败");
			$this->ajaxReturn(['status' => 1,'msg' => '操作成功']);
    	}
    }
    
    public function positionHandle(){
        $data = I('post.');
        if($data['act'] == 'add'){
            $r = M('ad_position')->add($data);
        }
        
        if($data['act'] == 'edit'){
        	$r = M('ad_position')->where('position_id',$data['position_id'])->save($data);
        }
        
        if($data['act'] == 'del'){
        	if(M('ad')->where('pid',$data['position_id'])->count()>0){
        		$this->error("此广告位下还有广告，请先清除",U('Admin/Ad/positionList'));
        	}else{
        		$r = M('ad_position')->where('position_id', $data['position_id'])->delete();
        		if($r) exit(json_encode(1));
        	}
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U('Admin/Ad/positionList');
        if($r){
        	$this->success("操作成功",$referurl);
        }else{
        	$this->error("操作失败",$referurl);
        }
    }
    
/**
     * APP端编辑广告需要选择的商品
     * @return \think\mixed
     */
    public function search_goods()
    {
        $goods_id = I('goods_id/d');
        $keywords = I('keywords');
        $type = I('type/d',0); 
        $intro = input('intro');//推荐/新品
    
          
        $where = [];  //搜索条件       
        $storeid = session('store_id');		
		$where['storeid'] = $storeid;
		
		if($type>0){
			$where['type'] = $type;
		}
		
        if (!empty($goods_id)) {
            $where['id'] = array('notin', $goods_id);
        }
        

        if ($keywords) {
            $this->assign('keywords', $keywords);
            $where['gname'] = array('like', '%' . $keywords . '%');
        }

        $count = M('goods')->where($where)->count();
        $Page = new Page($count, 10);
        $goodsList = M('goods')->where($where)->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
//      $show = $Page->show();//分页显示输出
        $this->assign('page', $Page);//赋值分页输出
        $this->assign('goodsList', $goodsList);
        return $this->fetch();
    }
    
    public function changeAdField(){
        $field = $this->request->request('field');
    	$data[$field] = I('get.value');
    	$data['ad_id'] = I('get.ad_id');
    	M('ad')->save($data); // 根据条件保存修改的数据
    }
    
    public function ad_app_home(){
       
        return $this->fetch();
    }
    
	
    
    
    /**
     * 编辑广告中转方法
     */
    public function editAd()
    { 
        $img_url = I('img_url');
        $pid = I('pid/d',0); 
        \think\Cache::clear();        
        $request_url = I('request_url');
        //缓存请求的编辑广告URL
        session('ad_request_url' , $request_url);
        $request_url = urldecode(I('request_url'));
        $request_url = urldecode($request_url);
        $request_url = U($request_url,array('edit_ad'=>1,'img_url'=>$img_url,'pid'=>$pid));
        
        echo "<script>location.href='".$request_url."';</script>";
        exit;                
    }
	
	//添加编辑广告类型
	public function addeditadtype(){
		$id = I('atypeid/d',0);
		
		if ((I('is_ajax') == 1) && IS_POST) {
			$atypename = I('atypename/s','');
			
			$data = input('post.');
			$validate = \think\Loader::validate('AdType');
	        if (!$validate->batch()->check($data)) {
	            $error = $validate->getError();
	            $error_msg = array_values($error);
	            $return_arr = array(
	                'status' => -1,
	                'msg' => $error_msg[0],
	                'data' => $error,
	            );
	            $this->ajaxReturn($return_arr);
	        }
			
			
			if($id <= 0){
				$storeid = session('store_id');	
//				$data['storeid'] = 	$storeid;	
				M('ad_type')->add($data);
			}
			else{
				M('ad_type')->where(['atypeid'=>$id])->save($data);
			}
			$this->ajaxReturn(['status' => 1,'msg' => '操作成功','data' =>['url'=>U("Admin/Ad/adtypelist")]]);
		}
		
		$rinfo = Db::name('ad_type')->where('atypeid=' . I('GET.atypeid', 0))->find();
        $this->assign('rinfo', $rinfo);  // 商品详情
        return $this->fetch();
	}
	
	public function ajaxadtype(){
		$storeid = session('store_id');			
		$where = " storeid= $storeid "; // 搜索条件                              

        
        $count = M('ad_type')->count();
        $Page  = new AjaxPage($count,20);

        $show = $Page->show();
		
		$order_str = "atypeid desc";
        
        $aList = M('ad_type')->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('alist',$aList);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
	}
	
	public function adtypelist(){
		return $this->fetch();
	}
	
	
	public function delatype(){
		$ids = I('post.ids','');
        empty($ids) &&  $this->ajaxReturn(['status' => -1,'msg' =>"非法操作！",'data'  =>'']);
        $atypeid = rtrim($ids,",");
		
		$aresult = M("ad")->whereIn('atype',$ids)->select();
		if(count($aresult)>0){
			$this->ajaxReturn(['status' => -1,'msg' =>"已有广告使用此类型,请更改对应广告类型！",'data'  =>'']);
		}
		
        // 删除此角色      
        M("ad_type")->whereIn('atypeid',$atypeid)->delete();
		$this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Ad/adtypelist")]);  
	}
}